import axios from "axios"
import { Loading, Message} from 'element-ui'
import router from "@/router"
axios.defaults.baseURL="http://localhost:3000/"

let load = null;
export function showLoading(){
    load && load.close();
    load = Loading.service({
        locak:true,
        text:'请求中...',
        spinner:'el-icon-loading',
        background:'rgba(0,0,0,0.7)'
    })
}

export function showSuccess(msg){
    msg = msg || "请求成功"
    load && load.close();
    Message.success({
        message:msg,
        center:true,
        showClose:true
    })
}
export function showError(msg){
    msg = msg || "请求失败"
    load && load.close();
    Message.error({
        message:msg,
        center:true,
        showClose:true
    })
}

//请求发送前的拦截器
axios.interceptors.request.use(function(config){
    var token = sessionStorage.getItem("token");
    if(token){
        config.headers['token'] = token
    }
    
    showLoading()
    return config
},function(error){
    showError('请求发送失败')
    return Promise.reject(error)
})


//响应结束前的拦截器
axios.interceptors.response.use(function(response){
    console.log(response.data)
    setTimeout(()=>{
       if(response.data.type){
            showSuccess(response.data.msg);
        }else{
            if(response.data.type==0){
                showError(response.data.msg)
            }else{
                showSuccess(response.data.msg)
            }
        }
    },500)


    if(response.data.code=="3200"){
        //token有问题
        router.push({name:"login"})
    }
    return response

},function(error){
    showError('响应失败')
    return Promise.reject(error)
})


export const get =(url,params)=>{
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params
        })
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}

export const post =(url,params)=>{
    return new Promise(function(resolve,reject){
        axios.post(url,params)
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}
export {axios};